package com.njupt.car.controller;

import com.njupt.common.pojo.CookieUtils;
import com.njupt.common.pojo.JsonUtils;
import com.njupt.common.pojo.TaotaoResult;
import com.njupt.pojo.TbItem;
import com.njupt.pojo.TbUser;
import com.njupt.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 21:59 2018/6/4
 * @Modified By:
 **/
@Controller
public class CarController {

    @Value("${CART_KEY}")
    private String CART_KEY;
    @Value("${MAX_AGE}")
    private Integer MAX_AGE;
    @Autowired
    private ItemService itemService;


    /**
     * 添加购物车
     *
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/cart/add/{itemId}")
    public String addCarItem(@PathVariable Long itemId, @RequestParam(defaultValue = "1") Integer num,
                             HttpServletRequest request, HttpServletResponse response) {
        //1、从cookie中查询商品列表。
        List<TbItem> cartlist = getCartList(request);
        //2、判断商品在商品列表中是否存在。
        boolean flag = false;
        for (TbItem item : cartlist
                ) {
            //3、如果存在，商品数量相加。
            if (item.getId() == itemId.longValue()) {
                item.setNum(item.getNum() + num);
                flag = true;
                break;
            }
        }

        //4、不存在，根据商品id查询商品信息。
        if (!flag) {
            TbItem tbItem = itemService.getItemById(itemId);
            String image = tbItem.getImage();
            if (image != null) {
                String[] images = image.split(",");
                tbItem.setImage(images[0]);
            }
            tbItem.setNum(num);
            //5、把商品添加到购车列表。
            cartlist.add(tbItem);
        }


        //6、把购车商品列表写入cookie。
        CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartlist), MAX_AGE, true);
        return "cartSuccess";
    }

    /**
     * 从Cookie获取商品列表
     * @param request
     * @return
     */
    private List<TbItem> getCartList(HttpServletRequest request) {
        String json = CookieUtils.getCookieValue(request, CART_KEY, true);
        if (json == null) {
            return new ArrayList<>();
        }
        List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
        return list;
    }

    /**
     * 展示购物车
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/cart/cart")
    public String showCartList(HttpServletRequest request, Model model) {
        List<TbItem> itemList = getCartList(request);
        model.addAttribute("cartList", itemList);
        return "cart";
    }

    /**
     * 修改购物车商品数量
     *
     * @param num
     * @param itemId
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/cart/update/num/{itemId}/{num}")
    public TaotaoResult updateCart(@PathVariable Integer num, @PathVariable Long itemId,
                                   HttpServletRequest request, HttpServletResponse response) {

        List<TbItem> cartList = getCartList(request);
        for (TbItem item : cartList
                ) {
            if (item.getId() == itemId.longValue()) {
                item.setNum(num);
                break;
            }

        }
        CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartList), MAX_AGE, true);
        return TaotaoResult.ok();
    }


    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable Long itemId,
                                 HttpServletResponse response, HttpServletRequest request) {

        List<TbItem> cartList = getCartList(request);

        for (TbItem item : cartList
                ) {
            if (item.getId() == itemId.longValue()) {
                cartList.remove(item);
                break;
            }
        }
        CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartList), MAX_AGE, true);
        return "redirect:/cart/cart.html";
    }
}
